package jp.co.apl.haven.web.page;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import jp.co.apl.haven.generated.HavenProtos.AnswerList;
import jp.co.apl.haven.web.exception.ApplicationException;
import jp.co.apl.haven.web.service.HavenWebServiceImpl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.t2framework.t2.annotation.composite.POST;
import org.t2framework.t2.annotation.core.Default;
import org.t2framework.t2.annotation.core.Page;
import org.t2framework.t2.navigation.SimpleText;
import org.t2framework.t2.spi.Navigation;

import com.google.inject.Inject;

@Page
public class Upload {

    private Logger logger = LoggerFactory.getLogger(Upload.class);

    @Inject
    private HttpServletRequest request;

    @Inject
    private HavenWebServiceImpl havenWebService;

    @POST
    @Default
    public Navigation upload() {
        logger.info("upload start");

        try {
            AnswerList a = AnswerList.parseFrom(request.getInputStream());
            havenWebService.saveAll(a);
        } catch (IOException e) {
            logger.error("error", e);
            throw new ApplicationException("error");
        }

        logger.info("upload success");

        return SimpleText.out("OK");
    }
}
